import React, { useState, useEffect } from 'react'
import './index.scss'
import log from './img/log.svg'
import useMessage from 'antd/es/message/useMessage'
import { SendVerificationCode,verification,register,login } from '../../api'
import { useSelector, useDispatch } from 'react-redux'
import { decrement, reset } from '../../redux/reducer/stopwatch'
import { Md5 } from 'ts-md5'
import { useNavigate } from 'react-router-dom'
import { message } from 'antd'
export default function Login() {
    const navigate=useNavigate()
    const [state, setState] = useState(false)
    const [email, setEmail] = useState('')
    const [verificationCode, setVerificationCode] = useState('')
    const [password, setPassword] = useState('')
    const [confirmPassword, setconfirmPassword] = useState('')
    const [messageApi, contextHolder] = useMessage();
    const [CodeState, setCodeState] = useState(false)
    const stopwatch = useSelector((state: any) => state.stopwatch.value)
    const dispatch = useDispatch()
    const [loginEmail,setLoginEmail] = useState('')
    const [loginPassword,setLoginPassword] = useState('')
    useEffect(() => {
        if (CodeState && stopwatch !== 0) {
            var timer = setInterval(() => {
                dispatch(decrement())
            }, 1000)
        } else if (CodeState) { 
            setCodeState(false)
            dispatch(reset())
        }

        return () => {
            clearInterval(timer)
        }
    }, [stopwatch,CodeState,dispatch])
    function sendCode(e: React.MouseEvent<HTMLButtonElement>) {
        e.preventDefault()
        if (CodeState) {
            return
         }
        if (/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email)) {
            SendVerificationCode(email).then(res => {
                if (res.data.code === 0) {
                    messageApi.success('验证码发送成功')
                    setCodeState(true)
                } else { 
                    messageApi.warning(res.data.msg)
                }
            })
        } else {
            messageApi.warning('邮箱格式错误!')
        }
    }
    function registerbtn(e:React.MouseEvent<HTMLInputElement>) { 
        e.preventDefault()
        if (!/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email)) { 
            messageApi.warning('邮箱格式错误')
            return
        }
        if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(password)) { 
            messageApi.warning('密码至少八位数并包含数字和字母')
            return
        }
        if (confirmPassword!==password) { 
            messageApi.warning('两次输入密码不一致')
            return
        }
        if (verificationCode.trim()==='') { 
            messageApi.warning('请输入验证码')
        }
        verification(verificationCode, email).then(res => { 
            if (res.data.code === 0) { 
                register(email, Md5.hashStr(password)).then(res => { 
                    if (!res.data.code) {
                        messageApi.success('注册成功')
                        setState(false)
                    } else { 
                        messageApi.error('注册失败请稍后重试')
                    }
                    
                })
            }
        })
    }
    function Login(e: React.MouseEvent<HTMLInputElement>) { 
        e.preventDefault()
        if (!/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(loginEmail)) { 
            messageApi.warning('邮箱格式错误')
            return
        }
        login(loginEmail, Md5.hashStr(loginPassword)).then(res => { 
            if (res.data.code === 1) {
                message.success('登录成功')
                localStorage.token = res.data.token
                setTimeout(() => { 
                    navigate('/home/user')
                },1000)
                
            } else { 
                messageApi.error('账号或密码错误')
            }
        }).catch(() => { 
            messageApi.error('账号或密码错误')
        })
    }
    return (
        <div className={`container ${state ? 'sign-up-mode' : ''}`}>
            {contextHolder}
            <div className="forms-container">
                <div className="signin-signup">
                    <form action="#" className="sign-in-form">
                        <h2 className="title">登录</h2>
                        <div className="input-field">
                            <i className="fas fa-user"></i>
                            <input type="text" value={loginEmail} onChange={(e:React.ChangeEvent<HTMLInputElement>) => { setLoginEmail(e.target.value)}} placeholder="邮箱" />
                        </div>
                        <div className="input-field">
                            <i className="fas fa-lock"></i>
                            <input type="password" value={loginPassword} onChange={(e:React.ChangeEvent<HTMLInputElement>) => {setLoginPassword(e.target.value) }} placeholder="密码" />
                        </div>
                        <input type="submit" onClick={(e:React.MouseEvent<HTMLInputElement>) => { Login(e)}} value="登 录" className="btn solid" />
                    </form>
                    <form action="#" className="sign-up-form">
                        <h2 className="title">注册</h2>
                        <div className="input-field">
                            <i className="fas fa-envelope"></i>
                            <input type="email" value={email} onChange={(e) => { setEmail(e.target.value) }} placeholder="邮箱" />
                            <button className='btn' onClick={(e: React.MouseEvent<HTMLButtonElement>) => sendCode(e)}>
                                {CodeState?stopwatch<10?'0'+stopwatch:stopwatch:'获取验证码'}
                            </button>
                        </div>
                        <div className="input-field">
                            <i className="fas fa-envelope"></i>
                            <input type="email" value={verificationCode} onChange={e => { setVerificationCode(e.target.value) }} placeholder="验证码" />
                        </div>
                        <div className="input-field">
                            <i className="fas fa-lock"></i>
                            <input type="password" value={password} onChange={e => { setPassword(e.target.value) }} placeholder="密码" />
                        </div>
                        <div className="input-field">
                            <i className="fas fa-lock"></i>
                            <input type="password" value={confirmPassword} onChange={e => { setconfirmPassword(e.target.value) }} placeholder="确认密码" />
                        </div>
                        <input type="submit" onClick={(e:React.MouseEvent<HTMLInputElement>)=>registerbtn(e)} className="btn" value="注 册" />
                    </form>
                </div>
            </div>

            <div className="panels-container">
                <div className="panel left-panel">
                    <div className="content">
                        <h3>新用户?</h3>
                        <p>
                            好兄弟,你来了,我们的网站就差你的加入了,点击下方注册按钮加入我们吧!!
                        </p>
                        <button onClick={() => { setState(!state) }} className="btn transparent" id="sign-up-btn">
                            注册
                        </button>
                    </div>
                    <img src={log} className="image" alt="" />
                </div>
                <div className="panel right-panel">
                    <div className="content">
                        <h3>已经是我们自己人了吗?</h3>
                        <p>
                            那好兄弟,你直接点击登录按钮,登录到我们这优秀的系统里!!
                        </p>
                        <button onClick={() => { setState(!state) }} className="btn transparent" id="sign-in-btn">
                            登 录
                        </button>
                    </div>
                    <img src={log} className="image" alt="" />
                </div>
            </div>
        </div>
    )
}
